package com.zhiqianbao.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.zhiqianbao.R;
import com.zhiqianbao.adapter.MessageListAdapter;
import com.zhiqianbao.entity.CustomerServiceRecord;
import com.zhiqianbao.entity.Result;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.HttpUtils;
import com.zhiqianbao.view.RefreshableView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import cn.trinea.android.common.util.StringUtils;

/**
 * Created by liang on 2016/2/18.
 */
public class MessageMainActivity extends BaseActivity implements View.OnClickListener {
    /**
     * 半分钟从数据取一次数据
     */
    private long mTime = 5000;

    Runnable timeRunnable;
    RefreshableView refreshableView;
    ListView lvMsg;
    EditText editTxtMsg;
    Button btnSend;

    MessageListAdapter messageListAdapter;

    Long firstDisplayTime = null;

    boolean noGetMessages = false;

    /**
     * 消息列表显示
     */
    List<CustomerServiceRecord> csrs = new ArrayList<>();

    Handler messagesHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RESULT_CANCELED:
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case RESULT_OK:
                    Result<List<Object>> data = (Result<List<Object>>) msg.obj;
                    if(data!=null) {
                        if (data.getCode().equals(Constants.DEFAULT_SUCCESS_CODE)) {
                            try {
                                List<Object> objs = data.getData();
                                //如果最新消息不够10条，从本地取出几条 凑够10条
                                if (objs.size() < 10) {
                                    int count = 10 - objs.size();
                                    List<CustomerServiceRecord> customerServiceRecords = CustomerServiceRecord.findWithQuery(CustomerServiceRecord.class, "select * from customer_service_record where user_id = ? order by create_time desc limit " + count, Constants.LOGIN_USER.getId() + "");
                                    if (!customerServiceRecords.isEmpty()) {
                                        csrs.addAll(customerServiceRecords);
                                    }
                                }
                                for (Object obj : objs) {
                                    CustomerServiceRecord csr = gson.fromJson(gson.toJson(obj), CustomerServiceRecord.class);
                                    csr.save();
                                    csrs.add(csr);
                                }

                                Collections.sort(csrs, new Comparator<CustomerServiceRecord>() {
                                    @Override
                                    public int compare(CustomerServiceRecord lhs, CustomerServiceRecord rhs) {
                                        if (lhs.getCreateTime() > rhs.getCreateTime()) {
                                            return 1;
                                        } else {
                                            return -1;
                                        }
                                    }
                                });

                                messageListAdapter = new MessageListAdapter(MessageMainActivity.this, csrs);
                                lvMsg.setAdapter(messageListAdapter);
                                lvMsg.setSelection(lvMsg.getCount() - 1);
                            } catch (Exception e) {

                            }
                        } else {
                            showShortToast1(data.getMsg());
                        }
                    }
                    break;
            }
            closeWaitDialog();
        }
    };

    Handler alwaysHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RESULT_CANCELED:
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case RESULT_OK:
                    Result<List<Object>> data = (Result<List<Object>>) msg.obj;
                    if(data!=null) {
                        if (data.getCode().equals(Constants.DEFAULT_SUCCESS_CODE)) {
                            List<Object> objs = data.getData();
                            if (objs.isEmpty()) {
                                return;
                            }
                            List<CustomerServiceRecord> newCsrs = new ArrayList<>();
                            for (Object obj : objs) {
                                CustomerServiceRecord csr = gson.fromJson(gson.toJson(obj), CustomerServiceRecord.class);
                                csr.save();
                                newCsrs.add(csr);
                            }

                            Collections.sort(newCsrs, new Comparator<CustomerServiceRecord>() {
                                @Override
                                public int compare(CustomerServiceRecord lhs, CustomerServiceRecord rhs) {
                                    if (lhs.getCreateTime() > rhs.getCreateTime()) {
                                        return 1;
                                    } else {
                                        return -1;
                                    }
                                }
                            });
                            csrs.addAll(newCsrs);

                            messageListAdapter = new MessageListAdapter(MessageMainActivity.this, csrs);
                            lvMsg.setAdapter(messageListAdapter);
                            lvMsg.setSelection(lvMsg.getCount() - 1);
                        } else {
                            showShortToast1(data.getMsg());
                        }
                    }
                    break;
            }
        }
    };

    Handler sendMessageHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RESULT_CANCELED :
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case RESULT_OK :
                    Result<CustomerServiceRecord> data = (Result<CustomerServiceRecord>) msg.obj;
                    if(data!=null) {
                        if (data.getCode().equals(Constants.DEFAULT_SUCCESS_CODE)) {
                            CustomerServiceRecord customerServiceRecord = data.getData();
                            customerServiceRecord.save();
                            //本地app显示
                            csrs.add(customerServiceRecord);
                            messageListAdapter.notifyDataSetChanged();
                            lvMsg.setSelection(lvMsg.getCount() - 1);
                            editTxtMsg.setText("");
                        } else {
                            showShortToast1(data.getMsg());
                        }
                    }
                    break;
            }
            btnSend.setClickable(true);
        }
    };

    private Handler timerHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message_main);
        init();
        initView();
    }

    private void initView() {
         refreshableView=(RefreshableView)findViewById(R.id.refreshable_view);
         lvMsg=(ListView)findViewById(R.id.lv_msg);
         editTxtMsg=(EditText)findViewById(R.id.editTxt_msg);
         btnSend=(Button)findViewById(R.id.btn_send);

        //根据登录用户调用服务器消息记录
        if(Constants.LOGIN_USER!=null) {
            getMessagesByServer();
        }

        //添加下拉事件
        refreshableView.setOnRefreshListener(new RefreshableView.PullToRefreshListener() {
            @Override
            public void onRefresh() {
                noGetMessages = true;
                if (!csrs.isEmpty()) {
                    //取出显示的消息的最早时间
                    CustomerServiceRecord csr = csrs.get(0);
                    if (null != csr) {
                        firstDisplayTime = csr.getCreateTime();
                    }
                    //通过时间 向上取十条
                    List<CustomerServiceRecord> customerServiceRecords = CustomerServiceRecord.findWithQuery(CustomerServiceRecord.class, "select * from customer_service_record where user_id = ? and create_time < ? order by create_time desc limit 10", Constants.LOGIN_USER.getId() + "", firstDisplayTime.toString());
                    if (!customerServiceRecords.isEmpty()) {
                        csrs.addAll(customerServiceRecords);
                        Collections.sort(csrs, new Comparator<CustomerServiceRecord>() {
                            @Override
                            public int compare(CustomerServiceRecord lhs, CustomerServiceRecord rhs) {
                                if (lhs.getCreateTime() > rhs.getCreateTime()) {
                                    return 1;
                                } else {
                                    return -1;
                                }
                            }
                        });
                        lvMsg.deferNotifyDataSetChanged();
                    }
                }
                refreshableView.finishRefreshing();
                noGetMessages = false;
            }
        }, 0);

        //每隔一段时间 访问一次数据库取出客服消息
        timeRunnable = new Runnable() {
            @Override
            public void run() {
                Log.d(MessageMainActivity.class.getSimpleName(), "轮询服务器获取消息");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //如果处于下拉刷新状态，不进行查询服务器，防止冲突
                        if (noGetMessages) {
                            return;
                        }
                        Map<String, String> params = new HashMap<>();
                        params.put("userId",Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                        params.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                        String result = HttpUtils.httpPostString(Constants.API_ROOT + "/message/getMessages", params, MessageMainActivity.this);
                        Message message = new Message();
                        if (StringUtils.isBlank(result)) {
                            message.what = RESULT_CANCELED;
                        } else {
                            message.what = RESULT_OK;
                            Result<List<CustomerServiceRecord>> data = Result.fromJson(result, List.class);
                            message.obj = data;
                        }
                        alwaysHandler.sendMessage(message);

                    }
                }).start();
                timerHandler.postDelayed(this, mTime);
            }
        };

        timerHandler.postDelayed(timeRunnable, mTime);



        btnSend.setOnClickListener(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        timerHandler.removeCallbacks(timeRunnable);
    }

    @Override
    public void onClick(View v) {
        if(R.id.btn_send==v.getId()){
                String message = editTxtMsg.getText().toString();
                if (StringUtils.isBlank(message)) {
                    return;
                }
                sendMessage(message);
        }
    }

    /**
     * 获取消息
     */
    private void getMessagesByServer() {
       /* //查询本地有没有消息 且最后一条消息的时间
        Long userId = Constants.LOGIN_USER.getId();
        List<CustomerServiceRecord> customerServiceRecords = CustomerServiceRecord.findWithQuery(CustomerServiceRecord.class, "select * from customer_service_record where user_id = ? order by create_time desc limit 1", userId.toString());
        CustomerServiceRecord customerServiceRecord = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        final String lastTime;
        if (!customerServiceRecords.isEmpty()) {
            customerServiceRecord = customerServiceRecords.get(0);
            lastTime = sdf.format(new Date(customerServiceRecord.getCreateTime()));
        } else {
            lastTime = "";
        }*/
        showWaitDialog();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Map<String, String> params = new HashMap<>();
              /*  if (!StringUtils.isBlank(lastTime)) {
                    params.put("lastTime", lastTime);
                }*/
                params.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                params.put("userId",Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/message/getMessages", params, MessageMainActivity.this);
                Message message = new Message();
                if (StringUtils.isBlank(result)) {
                    message.what = RESULT_CANCELED;
                } else {
                    message.what = RESULT_OK;
                    Result<List<CustomerServiceRecord>> data = Result.fromJson(result, List.class);
                    message.obj = data;
                }
                messagesHandler.sendMessage(message);
            }
        }).start();
    }

    /**
     * 发送信息
     * @param message
     */
    private void sendMessage(final String message) {
        btnSend.setClickable(false);
        //调用发送接口
        new Thread(new Runnable() {
            @Override
            public void run() {
                Map<String, String> params = new HashMap<>();
                params.put("message", message);
                params.put("userId",Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                params.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/message/send", params, MessageMainActivity.this);
                Message sm = new Message();
                if (StringUtils.isBlank(result)) {
                    sm.what = RESULT_CANCELED;
                } else {
                    sm.what = RESULT_OK;
                    Result<CustomerServiceRecord> data = Result.fromJson(result, CustomerServiceRecord.class);
                    sm.obj = data;
                }

                sendMessageHandler.sendMessage(sm);
            }
        }).start();
    }

    @Override
    public void onPause() {
        super.onPause();
        sendRefreshReceiver();
    }

    /**
     * 通知主页面刷新消息提醒
     */
    public void sendRefreshReceiver(){
        Intent intent=new Intent();
        intent.setAction(MainActivity.REFRESH_MSGS);
        sendBroadcast(intent);
    }
}
